package gao.xioalei.dao;

import gao.xioalei.entity.Message;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("MessageDao")
public interface MessageDao extends JpaRepository<Message, String> {

    public List<Message> findAllByReceiverAndIsReadOrderByShowOrderAsc(String receiver, boolean isRead);

    @Query(value = "select coalesce(max(show_order),0) from chat_message where sender=:sender and receiver=:receiver or sender=:receiver and receiver=:sender", nativeQuery = true)
    public Integer getMaxOrderBySenderAndReceiver(@Param("sender") String sender,
                                                  @Param("receiver") String receiver);

    @Query("update Message set isRead=:isRead where id=:id")
    @Modifying
    public void updateIsRead(@Param("isRead") boolean isRead,
                             @Param("id") String id);

    public Page<Message> findAllByReceiverAndSenderOrReceiverAndSenderOrderByShowOrderDesc(String receiver1, String sender1, String receiver2, String sender2, Pageable pageable);

    @Query(value = "from Message where (receiver=:receiver1 and sender=:sender1 or receiver=:receiver2 and sender=:sender2) and showOrder <:showOrder",
            countQuery = "select count(*) from Message where (receiver=:receiver1 and sender=:sender1 or receiver=:receiver2 and sender=:sender2) and showOrder <:showOrder")
    public Page<Message> findAllByReceiverAndSenderOrReceiverAndSenderAndShowOrderBeforeOrderByShowOrderDesc(@Param("receiver1") String receiver1, @Param("sender1") String sender1, @Param("receiver2") String receiver2, @Param("sender2") String sender2, @Param("showOrder") Integer showOrder, Pageable pageable);

    @Query("select showOrder from Message where id=:id")
    public Integer getShowOrderById(@Param("id") String id);
}
